import { h, mergeProps, onBeforeMount, onBeforeUnmount, render } from 'vue'

export const useCompInstance = (opts = {}) => {
    const { component = null, props = {}, slots = {}} = opts
    let vnode = h(component, mergeProps(props), slots)
    let dom

    const destroy = () => {
        render(null, dom)
        document.body.removeChild(dom)
        vnode = null
        dom = null
    }

    onBeforeMount(() => {
        dom = document.createElement('div')
        render(vnode, dom)
        document.body.appendChild(dom)
    })

    onBeforeUnmount(() => {
        destroy()
    })

    const getComponent = () => {
        return vnode.component
    }

    const getExposed = () => {
        return getComponent().exposed
    }

    return {
        getComponent,
        getExposed,
        destroy
    }
}